package com.example.mypresentationdemo.presentationViews;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.blankj.utilcode.util.FileUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.example.mypresentationdemo.Constants;
import com.example.mypresentationdemo.Data;
import com.example.mypresentationdemo.R;
import com.example.presentation_libary.presentationViews.BasePresentionView;

import java.io.File;
import java.io.FileFilter;
import java.util.List;

/**
 * 我是商品广告的
 */
public class DislayProductAdvView extends BasePresentionView {
    public static final String Tag = "商品广告页";


    public DislayProductAdvView(@NonNull Context context, String mjson) {
        super(context, mjson);
    }

    @Override
    public int getLayoutId() {
        return R.layout.view_auxiliary_product_adv;
    }


    public void initEvent() {
        Log.i(Tag, json);
        Data data = GsonUtils.fromJson(json, Data.class);
        TextView advTv = rootView.findViewById(R.id.tv_adv_content);
        advTv.setText("商品货道-" + data.getName());
        ImageView img_product_adv = rootView.findViewById(R.id.img_product_adv);
        if (FileUtils.isDir(Constants.DIR_AUXILIARY)) {
            List<File> files = getFiles(data.getName() + "-");
            if (files.size() > 0) {
                Bitmap bitmap = BitmapFactory.decodeFile(files.get(0).getAbsolutePath());
                img_product_adv.setImageBitmap(bitmap);
            } else {
                img_product_adv.setImageResource(R.mipmap.ic_launcher_round);
            }
        } else {
            Log.i(Tag, "文件路径= 不存在");
        }
    }

    /**
     *
     * 查询文件夹下的所有文件 及进行条件过滤
     * @param str_fixe
     * @return
     */
    public List<File> getFiles(final String str_fixe) {
        List<File> files = FileUtils.listFilesInDirWithFilter(Constants.DIR_AUXILIARY, new FileFilter() {
            @Override
            public boolean accept(File pathname) {
                boolean contains = pathname.getName().startsWith(str_fixe) && isImg(pathname.getName());
                return contains;
            }
        });
        Log.i(Tag, "文件数量=" + files.size() + "");
        return files;
    }

    /**
     * 判断后缀名是否是图片格式
     *
     * @param pathname
     * @return
     */
    public boolean isImg(String pathname) {
        if (pathname.endsWith(".jpg") || pathname.endsWith(".png") || pathname.endsWith(".webp")) {
            return true;
        }
        return false;
    }
}
